package name.bingo.bing.concurrent.red.packet.facade;

import lombok.extern.slf4j.Slf4j;
import name.bingo.bing.concurrent.red.packet.dao.TRedPacketDao;
import name.bingo.bing.concurrent.red.packet.dao.TUserRedPacketDao;
import name.bingo.bing.concurrent.red.packet.manager.RedPacketManager;

import name.bingo.bing.concurrent.red.packet.model.TRedPacket;
import name.bingo.bing.concurrent.red.packet.model.TUserRedPacket;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.Date;

/**
 * 红包模块对外服务
 *
 * @author [ your email ]
 * @date 2019-03-22 11:09:52
 * Created by CodeGen .
 */
@Slf4j
@Service
public class TRedPacketReadFacade {
    private static final BigDecimal UNITAMOUNT=new BigDecimal(10);

    @Autowired
    private TRedPacketDao tRedPacketDao;
    @Autowired
    private TUserRedPacketDao tUserRedPacketDao;

    /**
     * 抢红包操作
     * @param:
     * @return:
     */
    @Transactional(isolation = Isolation.READ_COMMITTED ,
            propagation = Propagation.REQUIRED ,
            rollbackFor = Exception.class)
    public Boolean grapRedPacket(Long redPacketId,Long customerId){
        System.out.println(new Date().getTime());
        Boolean result=false;
        try {
            Boolean update = doMoreTimes(redPacketId);
            if(!update){
                return update;
            }
        }catch (Exception e){
            System.out.println(e.getMessage());
        }

        TUserRedPacket tUserRedPacket=new TUserRedPacket();
        tUserRedPacket.setCustomerId(customerId);
        tUserRedPacket.setRedPacketId(redPacketId);
        tUserRedPacket.setAmount(UNITAMOUNT);
        result = tUserRedPacketDao.create(tUserRedPacket);
        return result;
    }

    public Boolean doMoreTimes(Long redPacketId)throws Exception{
        int times=3;
        while(times>0){
            times--;
            TRedPacket redPacket = tRedPacketDao.findById(redPacketId);
            if (redPacket==null || redPacket.getStock()<=0){
                return false;
            }
            Boolean update = tRedPacketDao.decreaseRedPacket(redPacketId,redPacket.getVersion());
            if(update){
                return update;
            }
            Thread.sleep(10);
        }
        return false;
    }


}
